package Book;
import constant.constant;
import Utils.AnalyzingBook;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

public class Library {
    private Book[] books;
    public int bookCount;
    private Scanner scanner = Utils.ScannerSingleton.getScanner();
    private static Library library = new Library();
    private AnalyzingBook analyzingBook = new AnalyzingBook();
    private Library(){
        loadallbook();
    }
    public static Library getLibrary(){
        return library;
    }
    public void loadallbook(){
        try {
            Book[] allbook = analyzingBook.loadObject(constant.FileBOOK_NAME);
            books = new Book[constant.CAPCITY];
            if (allbook == null){
                bookCount = 0;
            }

            assert allbook != null;
            int Allbooklen = allbook.length;
            if (Allbooklen > books.length){
                books = new Book[Allbooklen];
            }
            for (int i = 0; i < Allbooklen; i++) {
                books[i] = allbook[i];
            }
            bookCount = Allbooklen;

        }catch(IOException e){
            throw new RuntimeException(e);
        }
    }
    private void storebook(){
        try {
            analyzingBook.storeObject(books, constant.FileBOOK_NAME);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public void searchBook() {
        System.out.println("请输入要查询的图书书名：");
        String title = scanner.nextLine();
        scanner.nextLine();
        Book book = searchBook(title);
        if (book == null){
            System.out.println(" 图书不存在！ ");
        }else {
            System.out.println(book);
        }
    }
    private Book searchBook(String title){
        library.loadallbook();
        System.out.println("执行Library查询图书的方法");
        for (int i = 0; i < bookCount; i++) {
            Book book1 = books[i];
            if (book1.getTitle().equals(title)){
                return book1;
            }
        }
        return null;
    }
    public Book searchBook(int bookid){
        library.loadallbook();
        System.out.println("执行Library查询图书的方法");
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if (book.getBookId() == bookid){
                return book;
            }
        }
        return null;
    }
    public void displaybook(){
        System.out.println("执行Library显示图书的方法");
        loadallbook();
        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i].toJson());
        }
    }
    public void exit(){
        System.out.println("Library退出系统");
        System.exit(0);
    }
    public void addBook(Book book){
        if(bookCount >= books.length) {
            System.out.println(" 图书馆已满，⽆法上架更多图书！ ");
            return;
        }
        //修改bookId为⾃增
//        book.setBookId(bookCount+1);
        Book bookcount = books[bookCount-1];
        book.setBookId(bookcount.getBookId()+1);
        books[bookCount++] = book;
        //此时存储数据的时候会把书籍对象全部存储，虽然部分属性没有输⼊赋值
        storebook();
        System.out.println(" 图书 "+book.getTitle()+" 上架成功！ ");
    }


    public void updatebook(Book book) {
        int index = SearchbyIdreturnIndex(book.getBookId());
        if (index == -1){
            System.out.println(" 图书编号不存在！ ");
            return;
        }
        books[index] = book;
        storebook();
    }
    private int SearchbyIdreturnIndex(int bookid){
        library.loadallbook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if (book.getBookId() == bookid){
                return i;
            }
    }
        return -1;
    }
    public void removeBook(int bookid) {
        int index = SearchbyIdreturnIndex(bookid);
        if (index == -1){
            System.out.println(" 图书编号不存在！ ");
            return;
        }
        for (int i = index; i < bookCount-1; i++){
            books[i] = books[i+1];
        }
        books[--bookCount] = null;
        storebook();
        System.out.println(" 删除图书成功！ ");


    }


    public void borrowcount() {
        loadallbook();
        for (int i = 0; i < bookCount; i++){
            Book book = books[i];
            System.out.println(" 图书编号："+book.getBookId()+" 借阅次数："+book.getBorrowCount());
        }
    }

    public void generateBook(int k) {
        loadallbook();
        Book[] bookArray = new Book[bookCount];
        for (int i = 0; i < bookCount; i++) {
            bookArray[i] = books[i];
        }
        Arrays.sort(bookArray);
        Book[] generateBooks = new Book[k];
        for (int i = 0; i < k; i++) {
            generateBooks[i] = bookArray[i];
        }
        System.out.println("最受欢迎的书籍：");
        for (int i = 0; i < k; i++) {
            System.out.println(generateBooks[i]);
        }

    }

    public void checkInventoryStatus() {
        loadallbook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if (book.isBorrowed()) {
                System.out.println(" 图书编号：" + book.getBookId() + " 借阅状态：已借出");
            } else {
                System.out.println(" 图书编号：" + book.getBookId() + " 借阅状态：未借出");
            }
        }
    }

    public void checkAndRemoveOldBooks() {
        loadallbook();
        long currentTime = System.currentTimeMillis();
        LocalDate currentDate = Instant.ofEpochMilli(currentTime).atZone(ZoneId.systemDefault()).toLocalDate();
        boolean flg = false;
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            LocalDate shelfDate = book.getShelfDate();
            Long days = ChronoUnit.DAYS.between(shelfDate, currentDate);
            if (days > 365) {
                System.out.println(" 图书编号：" + book.getBookId() + " 已 shelfDate 天数：" + days + "是否删除y/n");
                scanner.nextLine();
                String choice = scanner.nextLine();
                if (choice.equals("y")) {
                    removeBook(book.getBookId());
                    i--;
                }
                flg = true;
                if (!flg) {
                    System.out.println("没有超过上架一年的图书");
                }
            }
            storebook();

        }

    }
    private static int nextBookId = 1; // 添加这个字段
    // ... 其他现有代码

    // 添加获取下一个ID的方法
    public synchronized int getNextBookId() {
        return nextBookId++;
    }
    public int getlastBookCount() {
        return books[bookCount-1].getBookId()+1;
    }

    public void borrowbook(int bookid) {
        loadallbook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId()== bookid) {
                book.setBorrowed(true);
                book.increaseBorrowCount();
            }
        }
        storebook();
    }
    public void returnbook(int bookid) {
        loadallbook();
        Book book = searchBook(bookid);
        book.setBorrowed(true);
        book.decreaseBorrowCount();
        storebook();
    }
}
